package tcc.war.autenticador.util;
import java.io.IOException;
import java.io.Serializable;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import tcc.ejb.autenticador.entidade.Profissional;




public class VerificaPagina implements PhaseListener,Serializable { 

	private static final long serialVersionUID = 4874638488299039247L;
 
	public void afterPhase(PhaseEvent event) { 
		FacesContext fc = event.getFacesContext();
		String view = fc.getViewRoot().getViewId();
		boolean isPaginLogin = view.indexOf("login.xhtml") != -1;

		Profissional profissional = new Profissional();
		try{
			HttpSession session = (HttpSession) event.getFacesContext().getExternalContext().getSession(false); 
			profissional = (Profissional)session.getAttribute("PROFISSIONAL");
		}catch (Exception e) {
			profissional = null;
		}		
		if (!isPaginLogin && profissional == null) {
			ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();  
			HttpServletRequest request = (HttpServletRequest) context.getRequest(); 
			try {
				context.redirect(request.getContextPath() + "/paginas/login.tcc");
			} catch (IOException e) {
				e.printStackTrace();
			} 
		} 	
	} 
	public void beforePhase(PhaseEvent event) {}
	public PhaseId getPhaseId() { 
		return PhaseId.RESTORE_VIEW; 
	} 
} 